package com.alibaba.aliper.remote.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import com.alibaba.aliper.remote.proxy.ProxyException;
import com.alibaba.aliper.remote.proxy.protocol.HandShake;

public class ProxyServer implements Runnable{
	private ServerSocket serverSocket = null;
	private int port = 9119;
	
	private HashMap<String, Object> services = new HashMap<String, Object>();
	public <T> void registService(Class<T> inter,T service){
		if(!inter.isInterface()){
			throw new ProxyException("regist type must be an interface!");
		}
		String serviceName = inter.getName();
		if(services.containsKey(serviceName)){
			throw new ProxyException("service already exists!");
		}
		services.put(serviceName, service);
	}
	
	public static void main(String[] args) throws IOException {
		ProxyServer server = new ProxyServer();
		server.start();
	}

	public synchronized void start() throws IOException {
		this.initServerSocket();
		if(!this.running){
			this.running = true;
			Thread proxyServerThread = new Thread(this,"aliper-proxyServerThread");
			proxyServerThread.setDaemon(true);
			proxyServerThread.start();
		}
	}

	private void initServerSocket() throws IOException {
		this.serverSocket = new ServerSocket(this.port);
	}

	private boolean running = false;
	@Override
	public void run() {
		while(this.running){
			try {
				Socket socket = this.serverSocket.accept();
				String type = HandShake.readClientRequest(socket.getInputStream());
				if(this.services.containsKey(type)){
					
				}else{
					HandShake.writeServerAnswerFailed(socket.getOutputStream(),"service not exists!");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		this.running = false;
	}
}
